package com.mycontract.suitepro.components.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import com.mycontract.suitepro.R
import com.mycontract.suitepro.base.BaseDialogAction
import com.mycontract.suitepro.contract.ContractEvent
import com.mycontract.suitepro.databinding.DialogContractSuitePermissionsBinding
import com.mycontract.suitepro.extend.isContractSuiteAgreeContractSuiteSpecContractSuitePermissions
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil


class PermissionsDialog : DialogFragment(), BaseDialogAction {

    companion object {
        /**
         * 判断所有权限是否完成
         */
        fun checkAllPermissionAgreeWithoutSMS(contxt: Context): Boolean {
            var agreePhoneState = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_PHONE_STATE
                )
            ) {
                agreePhoneState = true
            }

            var agreeContacts = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_CONTACTS
                )
            ) {
                agreeContacts = true
            }

            var agreeCalllog = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_CALL_LOG
                )
            ) {
                agreeCalllog = true
            }

            return (agreePhoneState and agreeContacts && agreeCalllog)
        }

        /**
         * 判断所有权限是否完成
         */
        fun checkAllPermissionAgree(contxt: Context): Boolean {
            var agreeSms = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_SMS
                )
            ) {
                agreeSms = true
            }

            var agreePhoneState = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_PHONE_STATE
                )
            ) {
                agreePhoneState = true
            }

            var agreeContacts = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_CONTACTS
                )
            ) {
                agreeContacts = true
            }

            var agreeCalllog = false
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                    contxt,
                    android.Manifest.permission.READ_CALL_LOG
                )
            ) {
                agreeCalllog = true
            }

            return (agreeSms and agreePhoneState and agreeContacts and agreeCalllog)
        }

        /**
         * 获取待申请的权限列表
         * */
        fun getPermissionList(context: Context): List<PermissionItem> {
            val permissionList = mutableListOf<PermissionItem>()
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_SMS
                )
            ) {
                permissionList.add(
                    PermissionItem(
                        type = PermissionItem.TYPE_SMS,
                        permission = android.Manifest.permission.READ_SMS
                    )
                )
            }
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_CONTACTS
                )
            ) {
                permissionList.add(
                    PermissionItem(
                        type = PermissionItem.TYPE_CONTRACTS,
                        permission = android.Manifest.permission.READ_CONTACTS
                    )
                )
            }
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_CALL_LOG
                )
            ) {
                permissionList.add(
                    PermissionItem(
                        type = PermissionItem.TYPE_CALL_LOG,
                        permission = android.Manifest.permission.READ_CALL_LOG
                    )
                )
            }
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    context,
                    android.Manifest.permission.READ_PHONE_STATE
                )
            ) {
                permissionList.add(
                    PermissionItem(
                        type = PermissionItem.TYPE_PHONE_STATE,
                        permission = android.Manifest.permission.READ_PHONE_STATE
                    )
                )
            }
            // ab 面版本不加 app list 权限
//            if (permissionList.isNotEmpty()) {
//                permissionList.add(0, PermissionItem(type = PermissionItem.TYPE_APP))
//            }
            return permissionList
        }
    }

    //列表适配器
    private lateinit var mPermissionsAdapter: PermissionsAdapter

    //列表数据
    private val mPermissionList = mutableListOf<PermissionItem>()

    //布局句柄
    lateinit var mContractSuiteViewContractSuiteBinding: DialogContractSuitePermissionsBinding

    /**
     * 点击回调
     *
     * @return Boolean 是否为短信
     */
    private var mStartRequestPermissionClickListener: (type: Int) -> Unit = { }

    /**
     * phone state权限点击拒绝回调
     *
     */
    private var mPhoneSateDenyClickListener: () -> Unit = {}

    /**
     * sms 权限点击拒绝回调
     *
     */
    private var mSmsDenyClickListener: () -> Unit = {}

    /**
     * contacts 权限点击拒绝回调
     *
     */
    private var mContactsDenyClickListener: () -> Unit = {}

    /**
     * call log 权限点击拒绝回调
     *
     */
    private var mCalllogDenyClickListener: () -> Unit = {}

    /**
     * 所有权限点击同意回调
     *
     */
    private var mAllRequestPermissionAgreeListener: () -> Unit = {}

    /** fragmentManager */
    private var mfragmentManager: FragmentManager? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContractSuiteViewContractSuiteBinding =
            DialogContractSuitePermissionsBinding.inflate(layoutInflater)

        return mContractSuiteViewContractSuiteBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initContractSuiteSubviews()
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
//            it.setWindowAnimations(R.style.bottomDialogAnimation)
        }

        if (mPermissionList.size == 1) {
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge1.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge3.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.visibility = View.GONE

        } else if (mPermissionList.size == 2) {
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge1.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge3.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.visibility = View.GONE

        } else if (mPermissionList.size == 3) {
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge1.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge2.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge3.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.visibility = View.GONE

        } else if (mPermissionList.size == 4) {
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge1.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge2.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.visibility = View.VISIBLE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge3.visibility = View.VISIBLE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.visibility = View.VISIBLE

        } else {
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge1.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge2.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.visibility = View.GONE

            mContractSuiteViewContractSuiteBinding.vPermissionPageDotEdge3.visibility = View.GONE
            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.visibility = View.GONE
        }

        //设置fragment manager
        mPermissionsAdapter.setFragmentManager(mfragmentManager)
    }

    override fun initContractSuiteSubviews() {
        try {
            //初始化数据
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_APP))
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_SMS))
//            mPermissionList.add(PermissionItem(type = PermissionItem.TYPE_PHONE_STATE))

            //初始化适配器
            mPermissionsAdapter = PermissionsAdapter(requireContext(), mPermissionList)
            mPermissionsAdapter.setItemClickListener { action, permissionItem, position ->
                println("action: $action type: ${permissionItem.type}  position: $position")
                //如果是同意
                if (action == PermissionItem.RESULT_AGREE) {
                    if (permissionItem.type == PermissionItem.TYPE_APP) {
                        //如果是app list 直接展示下一个权限
                        setPermissionResult(PermissionItem.TYPE_APP, true)
                    } else {
                        mStartRequestPermissionClickListener.invoke(permissionItem.type)

                        if (permissionItem.type == PermissionItem.TYPE_PHONE_STATE) {
                            // 打点
                            AnalyticsUtil.saveHitPointInfo(
                                type = ContractEvent.PERMISSION_PHONE_STATE_AGREE,
                                remark = ""
                            )
                        } else if (permissionItem.type == PermissionItem.TYPE_SMS) {
                            // 打点
                            AnalyticsUtil.saveHitPointInfo(
                                type = ContractEvent.PERMISSION_SMS_AGREE,
                                remark = ""
                            )
                        } else if (permissionItem.type == PermissionItem.TYPE_CONTRACTS) {
                            // 打点
                            AnalyticsUtil.saveHitPointInfo(
                                type = ContractEvent.PERMISSION_CONTRACT_AGREE,
                                remark = ""
                            )
                        } else if (permissionItem.type == PermissionItem.TYPE_CALL_LOG) {
                            // 打点
                            AnalyticsUtil.saveHitPointInfo(
                                type = ContractEvent.PERMISSION_CALL_LOG_AGREE,
                                remark = ""
                            )
                        }
                    }
                } else {
                    if (permissionItem.type == PermissionItem.TYPE_PHONE_STATE) {
                        mPhoneSateDenyClickListener.invoke()

                        // 找下个拒绝引导页
                        setNexDenyPermissionPage(position)

                        // 打点
                        AnalyticsUtil.saveHitPointInfo(
                            type = ContractEvent.PERMISSION_PHONE_STATE_DENY,
                            remark = ""
                        )

                    } else if (permissionItem.type == PermissionItem.TYPE_SMS) {
                        mSmsDenyClickListener.invoke()

                        // 找下个拒绝引导页
                        setNexDenyPermissionPage(position)

                        // 打点
                        AnalyticsUtil.saveHitPointInfo(
                            type = ContractEvent.PERMISSION_SMS_DENY,
                            remark = ""
                        )

                    } else if (permissionItem.type == PermissionItem.TYPE_CONTRACTS) {
                        mContactsDenyClickListener.invoke()

                        // 找下个拒绝引导页
                        setNexDenyPermissionPage(position)

                        // 打点
                        AnalyticsUtil.saveHitPointInfo(
                            type = ContractEvent.PERMISSION_CONTRACT_DENY,
                            remark = ""
                        )

                    } else if (permissionItem.type == PermissionItem.TYPE_CALL_LOG) {
                        mCalllogDenyClickListener.invoke()

                        // 找下个拒绝引导页
                        setNexDenyPermissionPage(position)

                        // 打点
                        AnalyticsUtil.saveHitPointInfo(
                            type = ContractEvent.PERMISSION_CALL_LOG_DENY,
                            remark = ""
                        )

                    } else {
                        setPermissionResult(PermissionItem.TYPE_APP, false)
                    }
                }
            }

            mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.adapter =
                mPermissionsAdapter

            mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.pageMargin = 0
            mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.offscreenPageLimit = 3
            mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.addOnPageChangeListener(
                object : ViewPager.OnPageChangeListener {
                    override fun onPageScrolled(
                        position: Int,
                        positionOffset: Float,
                        positionOffsetPixels: Int
                    ) {
                    }

                    override fun onPageSelected(position: Int) {
                        //设置当前/总数

                        if (0 == position) {
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_yes
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )

                        } else if (1 == position) {
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_yes
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )

                        } else if (2 == position) {
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_yes
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )

                        } else {
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot1.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot2.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot3.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_no
                            )
                            mContractSuiteViewContractSuiteBinding.vPermissionPageDot4.setBackgroundResource(
                                R.drawable.contract_suite_permission_page_dot_yes
                            )
                        }
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }
                })

            mContractSuiteViewContractSuiteBinding.imageDialogPermissionClose.setOnClickListener {
                // 打点
                AnalyticsUtil.saveHitPointInfo(
                    type = ContractEvent.PERMISSION_CLOSE,
                    remark = ""
                )

                // 关闭
                dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun showContractSuiteWithContractSuiteUIContractSuiteTag(
        gTag: String,
        fragmentManager: FragmentManager
    ) {
    }

    override fun setContractSuiteOnContractSuiteActionContractSuiteClickContractSuiteListener(listener: (Int) -> Unit) {
    }

    /**
     * 设置数据源
     */
    fun setPermissionList(list: List<PermissionItem>) {
        mPermissionList.clear()
        mPermissionList.addAll(list)
    }

    /**
     * 更新视图
     */
    fun refresh() {
        mPermissionsAdapter.notifyDataSetChanged()
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setStartRequestPermissionClickListener(listener: (Int) -> Unit) {
        mStartRequestPermissionClickListener = listener
    }

    /**
     * 设置所有权限同意回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setAllRequestPermissionAgreeListener(listener: () -> Unit) {
        mAllRequestPermissionAgreeListener = listener
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setPhoneSateDenyClickListener(listener: () -> Unit) {
        mPhoneSateDenyClickListener = listener
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setSmsDenyClickListener(listener: () -> Unit) {
        mSmsDenyClickListener = listener
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setContractsDenyClickListener(listener: () -> Unit) {
        mContactsDenyClickListener = listener
    }

    /**
     * 设置点击回调
     *
     * @param Int 类型
     * @param RevObjAiHomeDemo 值
     */
    fun setCalllogDenyClickListener(listener: () -> Unit) {
        mCalllogDenyClickListener = listener
    }

    /** 设置权限操作结果 */
    fun setPermissionResult(type: Int, agree: Boolean) {
//        if (type == PermissionItem.TYPE_APP) {
//            mPermissionList.forEach { item ->
//                if (item.type == type) {
//                    item.result =
//                        if (agree) PermissionItem.RESULT_AGREE else PermissionItem.RESULT_DENY
//                }
//            }
//        }
        mPermissionList.forEach { item ->
            if (item.type == type) {
                item.result =
                    if (agree) PermissionItem.RESULT_AGREE else PermissionItem.RESULT_DENY
            }
        }

        //刷新页面
        mPermissionsAdapter.notifyDataSetChanged()

        //找出当前操作的页面
        var currIndex = 0
        for (curPageIndex in 0 until mPermissionList.size) {
            val item = mPermissionList[curPageIndex]
            if (item.type == type) {
                currIndex = curPageIndex
                break
            }
        }

        //如果是最后一个，跳回0
        if (currIndex == (mPermissionList.size - 1)) {
            currIndex = 0
        }

        //找出未同意的下一个页面
        var nextIndex = currIndex
        for (nextPageIndex in (currIndex) until mPermissionList.size) {
            val item = mPermissionList[nextPageIndex]
            if (!requireActivity().isContractSuiteAgreeContractSuiteSpecContractSuitePermissions(mutableListOf(item.permission))) {
                nextIndex = nextPageIndex
                break
            }
        }

        // 如果前面没有了，返回第1个
        if (nextIndex == currIndex) {
            currIndex = 0
            for (nextPageIndex in (currIndex) until mPermissionList.size) {
                val item = mPermissionList[nextPageIndex]
                if (!requireActivity().isContractSuiteAgreeContractSuiteSpecContractSuitePermissions(
                        mutableListOf(
                            item.permission
                        )
                    )
                ) {
                    nextIndex = nextPageIndex
                    break
                }
            }
        }

        //跳转
        mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.setCurrentItem(
            nextIndex,
            true
        )

        //判断下设备权限是否完成
        val agreeAll = checkAllPermissionAgree(requireContext())
        println("=============agreePhonState: $agreeAll")

        if (agreeAll) {
            mAllRequestPermissionAgreeListener.invoke()
            dismiss()
        }
    }

    /** 找到下一个拒绝的引导页面 */
    fun setNexDenyPermissionPage(position: Int) {
        //找出未同意的下一个页面
        var nextIndex = position
        for (nextPageIndex in (position + 1) until mPermissionList.size) {
            val item = mPermissionList[nextPageIndex]
            if (!requireActivity().isContractSuiteAgreeContractSuiteSpecContractSuitePermissions(
                    mutableListOf(item.permission)
                )
            ) {
                nextIndex = nextPageIndex
                break
            }
        }

        // 如果找不到，则从头搜索一次
        if (nextIndex == position) {
            for (nextPageIndex in 0 until position) {
                val item = mPermissionList[nextPageIndex]
                if (!requireActivity().isContractSuiteAgreeContractSuiteSpecContractSuitePermissions(
                        mutableListOf(item.permission)
                    )
                ) {
                    nextIndex = nextPageIndex
                    break
                }
            }
        }
        mContractSuiteViewContractSuiteBinding.viewpagerDialogPermissions.setCurrentItem(
            nextIndex,
            true
        )
    }

    fun setShowDiaog(fragmentManager: FragmentManager) {
        mfragmentManager = fragmentManager
        showNow(
            fragmentManager,
            PermissionsDialog::class.java.simpleName
        )
    }
}